
import { Service } from "./service";
import { PageDataRecord } from "entities"
import { AjaxOptions } from "maishu-chitu-service";
// import { contextName } from "../constants";
import { ComponentInfo } from "components/common/component";
import { contextName } from "json!websiteConfig";

export class LocalService extends Service {
    ajax<T>(url: string, options: AjaxOptions) {
        return super.ajax<T>(url, options);
    }
    private url(path: string): string {
        let contexts = requirejs.exec("contexts");
        let context: RequireContext = contexts[contextName];
        if (context != null && context.config != null && context.config.baseUrl != null) {
            return `${context.config.baseUrl}${path}`;
        }
        return `${path}`;
    }
    async savePageDataRecord(item: Partial<PageDataRecord>) {
        let r = await this.postByJson(this.url("page-data/save"), { item });
        Object.assign(item, r);
    }
    async getPageDataRecordByName(name: string): Promise<PageDataRecord> {
        let record = await this.get<PageDataRecord>(this.url("page-data/item"), { name });
        return record;
    }
    async getPageDataRecordById(id: string): Promise<PageDataRecord> {
        let record = await this.get<PageDataRecord>(this.url("page-data/item"), { id });
        if (record == null)
            return null;

        return record;
    }
    async clientFiles(): Promise<string[]> {
        let { protocol, host } = location;
        let r = await this.get<string[]>(this.url(`clientFiles`));
        return r;
    }
    async getDataObject<T>(key: string) {
        let r = await this.get<T>(this.url("data-object/get"), { key });
        return r;
    }
    async saveDataObject<T>(key: string, data: T) {
        let url = this.url("data-object/save");
        let r = await this.postByJson<T>(url, { key, data });
        return r;
    }

    private _componentInfos: ComponentInfo[];
    async componentInfos() {
        let url = this.url("user/componentInfos");
        if (this._componentInfos == null) {
            this._componentInfos = await this.get<ComponentInfo[]>(url);
            this._componentInfos.forEach(o => {
                if (o.path != null && o.path.endsWith(".js")) {
                    o.path = o.path.substr(0, o.path.length - ".js".length);
                }
            })
        }
        return this._componentInfos;
    }
}